package com.jzo2o.health.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.health.listener.ExcelListener;
import com.jzo2o.health.mapper.ReservationSettingMapper;
import com.jzo2o.health.model.domain.ReservationSetting;
import com.jzo2o.health.model.dto.request.ReservationSettingUpsertReqDTO;
import com.jzo2o.health.model.dto.response.ReservationDateResDTO;
import com.jzo2o.health.model.dto.response.ReservationSettingResDTO;
import com.jzo2o.health.model.excel.ReservationImportData;
import com.jzo2o.health.service.IReservationSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 预约设置 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-13
 */
@Service
public class ReservationSettingServiceImpl extends ServiceImpl<ReservationSettingMapper, ReservationSetting> implements IReservationSettingService {
    private static final int BATCH_SIZE = 100;

    @Resource
    ReservationSettingServiceImpl reservationSettingService;
    //@Resource
    //private IReservationSettingService service;
    @Resource
    private ReservationSettingMapper reservationSettingMapper;

    //根据给定的月份日期 获取该月份的所有预约设置信息
    @Override
    public void insertAll(MultipartFile file) throws IOException {
        EasyExcel
                .read(file.getInputStream(), ReservationSettingUpsertReqDTO.class, new ReadListener<ReservationSettingUpsertReqDTO>() {
                    private List<ReservationSettingUpsertReqDTO> list = new ArrayList<>();

                    @Override
                    public void invoke(ReservationSettingUpsertReqDTO data, AnalysisContext context) {
                        list.add(data);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                        reservationSettingService.saveBatch(list);
                    }
                })
                .sheet()
                .doRead();
    }

    public List<ReservationSettingResDTO> getReservationSettingByMonth(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M");
        YearMonth yearMonth = YearMonth.parse(date, formatter);
        // 继续处理 yearMonth

        //YearMonth yearMonth = YearMonth.parse(date);
        List<ReservationSetting> list = lambdaQuery()
                .ge(ReservationSetting::getOrderDate, yearMonth.atDay(1))
                .le(ReservationSetting::getOrderDate, yearMonth.atEndOfMonth()).list();
        List<ReservationSettingResDTO> resDTOS = new ArrayList<>();
        for (ReservationSetting setting : list) {
            ReservationSettingResDTO bean = BeanUtils.toBean(setting, ReservationSettingResDTO.class);
            bean.setDate(String.valueOf(setting.getOrderDate()));
            resDTOS.add(bean);
        }
        return resDTOS;
    }

    //根据提供的请求数据，编辑或更新某个日期的预约设置信息
    @Override
    public void editNumberByDate(ReservationSettingUpsertReqDTO reservationSettingUpsertReqDTO) {
        /*ReservationSetting bean = BeanUtils.toBean(reservationSettingUpsertReqDTO, ReservationSetting.class);
        bean.setReservations(0);
        boolean save = save(bean);
        if (!save) {
            throw new DBException("设置失败");
        }*/
        ReservationSetting bean = BeanUtils.toBean(reservationSettingUpsertReqDTO, ReservationSetting.class);
        bean.setReservations(0);

        // 查询是否已存在该日期的记录
        ReservationSetting existingSetting = lambdaQuery()
                .eq(ReservationSetting::getOrderDate, bean.getOrderDate())
                .one();

        if (existingSetting != null) {
            // 更新现有记录
            existingSetting.setNumber(bean.getNumber());
            boolean updateSuccess = updateById(existingSetting);
            if (!updateSuccess) {
                throw new DBException("更新失败");
            }
        } else {
            // 插入新记录
            boolean saveSuccess = save(bean);
            if (!saveSuccess) {
                throw new DBException("插入失败");
            }
        }
    }




        /*//从上传的 Excel 文件中读取预约设置数据，并进行相应的处理
        @Override
        public void excelReservation (MultipartFile file){
            try {
                EasyExcel.read(file.getInputStream(), ReservationImportData.class, new ExcelListener(service)).sheet().doRead();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }*/



    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ReservationSettingUpsertReqDTO> dtos) {
        List<ReservationSetting> entities = new ArrayList<>();
        for (ReservationSettingUpsertReqDTO dto : dtos) {
            ReservationSetting entity = new ReservationSetting();
            // 将 DTO 中的数据映射到实体对象
            entity.setOrderDate(dto.getOrderDate());
            entity.setNumber(dto.getNumber());
            // ... 设置其他属性 ...
            entities.add(entity);
        }
        // 调用 MyBatis-Plus 的批量保存方法
        this.saveBatch(entities);
    }

    //根据给定的月份，获取该月份的所有预约日期信息
    @Override
    public ReservationDateResDTO getReservationDateByMonth(String month) {
        YearMonth yearMonth = YearMonth.parse(month);
        List<String> dateList = reservationSettingMapper.getReservationDateByMonth(yearMonth.atDay(1), yearMonth.atEndOfMonth());
        return new ReservationDateResDTO(dateList);
    }
}




